package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthConstant;
import com.atguigu.common.constant.SmsConstant;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberVo;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.vo.LoginVo;
import com.atguigu.gulimall.auth.vo.RegistVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
public class LoginController {
    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostMapping("/regist")
    public String regist(@Valid RegistVo registVo, BindingResult result, RedirectAttributes redirectAttributes) {
        Map<String, String> map = new HashMap<>();
        if (result.hasErrors()) {
            //格式校验失败
            map = result.getFieldErrors().stream().collect(Collectors.toMap(f -> {
                return f.getField();
            }, f -> {
                return f.getDefaultMessage();
            }, (f1, f2) -> {
                return f1;
            }));
            //转发到注册页面会导致刷新页面重新提交表单，并且转发后的请求方式也不能改变；
            //重定向到页面可以用RedirectAttributes,底层使用的session
            //此方法保存：只要被使用一次就把session域中的数据清楚
            redirectAttributes.addFlashAttribute("errors", map);
            return "redirect:http://auth.gulimall.com/reg.html";
        } else {
            //校验验证码
            String code = redisTemplate.opsForValue().get(SmsConstant.SMS_CODE_PREFIX + registVo.getPhone());
            if (StringUtils.isNotEmpty(code)) {
                code=code.split("_")[0];
                if (code.equals(registVo.getCode())) {
                    //验证码验证成功，删除验证码
                    redisTemplate.delete(SmsConstant.SMS_CODE_PREFIX + registVo.getPhone());
                    //校验成功
                    //调用远程服务，注册用户
                    R r = memberFeignService.regist(registVo);
                    if (r.getCode() != 0) {
                        map.put("msg","远程调用注册失败");
                        return "redirect:http://auth.gulimall.com/reg.html";
                    }
                    else{
                        return "redirect:http://auth.gulimall.com/login.html";
                    }

                } else {
                    map.put("code", "验证码错误");
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            } else {
                map.put("code", "验证码错误");
                return "redirect:http://auth.gulimall.com/reg.html";
            }

        }

    }

    @PostMapping("/login")
    public String login(LoginVo loginVo, RedirectAttributes redirectAttributes, HttpSession session){
        R r = memberFeignService.login(loginVo);
        if(r.getCode()==0){
            //登录成功
            //TODO登陆成功的逻辑
            MemberVo member = r.getData(new TypeReference<MemberVo>() {
            });
            //把用户对象存入session中
            session.setAttribute(AuthConstant.LOGIN_USER,member);
            return "redirect:http://www.gulimall.com";
        }
        else {
            HashMap<String, String> map = new HashMap<>();
            map.put("msg",(String)r.get("msg"));
            redirectAttributes.addFlashAttribute("msg",map);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
